package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.AsyncImageLoader;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.AsyncImageLoader.ImageDownloadCallBack;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**商品类别
 * @author Administrator
 *
 */
public class Shop1 extends Activity
{
	private Shop1 oThis = this;
	private GridView gridView;
	private List<Map<String, Object>> list;
	private MyAdapter myAdapter;
	public static Shop1 instance = null;
	CustomProgressDialog proDialog;// 加载框

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.shop1_main);
		MyApplication myApplication;
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		instance = this;
		findView();

		getData();

		setListener();
	}

	private void findView()
	{
		gridView = (GridView) this.findViewById(R.id.gridView);
		list = new ArrayList<Map<String, Object>>();
		myAdapter = new MyAdapter(this);
	}

	private void setListener()
	{
		gridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				TextView tv_lb = (TextView) arg1.findViewById(R.id.gridview_textview);
				TextView tv_lbid = (TextView) arg1.findViewById(R.id.gridview_lbid);
				TextView tv_index = (TextView) arg1.findViewById(R.id.gridview_index);
				String lb = tv_lb.getText().toString().trim();
				String index = tv_index.getText().toString().trim();
				String lbid = tv_lbid.getText().toString().trim();

				Intent intent = new Intent(Shop1.this, Shop2.class);
				intent.putExtra("lb", lb);
				intent.putExtra("lbid", lbid);
				intent.putExtra("index", index);
				// startActivity(intent);
				// 把Activity转换成一个Window，然后转换成View
				Window w = ShopMarket.group.getLocalActivityManager().startActivity("Shop2", intent);
				View view = w.getDecorView();
				// 设置要跳转的Activity显示为本ActivityGroup的内容
				ShopMarket.group.setContentView(view);
			}
		});
	}

	private void getData()
	{
		proDialog = CustomProgressDialog.createDialog(oThis.getParent());
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", "0"));

			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.SPLBNAME, ls);

			if (json != null && !json.equals(""))
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (new JSONArray(json.getString("lbinfo")).length() > 0)
					{
						// 获取收费信息
						JSONArray jsonArr = new JSONArray(json.getString("lbinfo"));
						JSONObject js = null;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							Map<String, Object> map = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							map.put("index", String.valueOf(i));
							map.put("name", js.getString("lbname"));
							// String strId = js.getString("id");
							map.put("lbid", js.getString("id"));
							map.put("imgname", js.getString("imgpath"));

							// // 获取图片
							// List<NameValuePair> ls1 = new ArrayList<NameValuePair>();
							// ls1.add(new BasicNameValuePair("id", strId));
							// Bitmap bitmap = HTTPGetTool.getTool()
							// .queryByteForPost(
							// URLUtils.HOST + URLUtils.SPLBPIC,
							// ls1);
							// map.put("pic", bitmap);
							list.add(map);
						}

						bundle.putInt("type", 0);
						bundle.putString("msg", "");
					}
					else
					{
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				}
				else
				{
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}

			}
			else
			{
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Bundle bundle = new Bundle();
			bundle.putInt("type", -1);
			bundle.putString("msg", e.toString());
			Message msg = myHandler.obtainMessage();
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}

	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
				case 0:
					proDialog.dismiss();
					setData();
					break;
				default:
					break;
			}
		};
	};

	private void setData()
	{

		myAdapter.setList(list);
		gridView.setAdapter(myAdapter);

		// 初始化全局变量
		MyApplication myApp = (MyApplication) this.getApplication();
		List<Map<String, Object>>[] list_gwc = new List[list.size()];
		List<Integer>[] list_position = new List[list.size()];
		for (int i = 0; i < list.size(); i++)
		{
			list_gwc[i] = new ArrayList<Map<String, Object>>();
			list_position[i] = new ArrayList<Integer>();
		}
		myApp.setList_gwc(list_gwc);
		myApp.setList_position(list_position);

	}

	class MyAdapter extends BaseAdapter
	{
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;
		private AsyncImageLoader imageLoader = new AsyncImageLoader(getApplicationContext());

		MyAdapter(Context context)
		{
			mLayoutInflater = LayoutInflater.from(context);
		}

		public List<Map<String, Object>> getList()
		{
			return list;
		}

		public void setList(List<Map<String, Object>> list)
		{
			this.list = list;
		}

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null)
			{
				convertView = mLayoutInflater.inflate(R.layout.shop_gridlist, null);
				holder = new ViewHolder();
				holder.gridview_imageview = (ImageView) convertView.findViewById(R.id.gridview_imageview);
				holder.gridview_textview = (TextView) convertView.findViewById(R.id.gridview_textview);
				holder.gridview_index = (TextView) convertView.findViewById(R.id.gridview_index);
				holder.gridview_lbid = (TextView) convertView.findViewById(R.id.gridview_lbid);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}

			final String strId = (CharSequence) list.get(position).get("lbid") == null ? "" : list.get(position).get("lbid").toString();
			final String imgname = (CharSequence) list.get(position).get("imgname") == null ? "" : list.get(position).get("imgname")
					.toString();

			Bitmap bitmap = null;
			if (!imgname.equals(""))
			{
				bitmap = imageLoader.loadImageByname(holder.gridview_imageview, imgname, URLUtils.HOST + URLUtils.SPLBPICBYNAME,
						new ImageDownloadCallBack()
						{
							@Override
							public void onImageDownloaded(ImageView imageView, Bitmap bitmap)
							{
								imageView.setImageBitmap(bitmap);

							}
						});

				if (bitmap != null)
				{
					holder.gridview_imageview.setImageBitmap(bitmap);
				}
			}

			holder.gridview_textview.setText((CharSequence) list.get(position).get("name"));
			holder.gridview_index.setText((CharSequence) list.get(position).get("index"));
			holder.gridview_lbid.setText((CharSequence) list.get(position).get("lbid"));
			return convertView;
		}
	}

	public class ViewHolder
	{
		private ImageView gridview_imageview;
		private TextView gridview_textview;
		private TextView gridview_index;
		private TextView gridview_lbid;
	}

}
